package com.springboot.myspringboot.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.myspringboot.config.Result;
import com.springboot.myspringboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        log.info(requestURI);
        log.info(requestURI.substring(0,6));
        if(requestURI.equals("/index/login") || requestURI.startsWith("/files")){
           return true;
        }
        String tokenName = "Authorization";
        String token = request.getHeader(tokenName);
        if(token == null){
            token = request.getParameter(tokenName);
        }

        if(token == null || token.isEmpty()){
            PrintWriter writer = response.getWriter();
            ObjectMapper obj = new ObjectMapper();
            String errString = obj.writeValueAsString(Result.error("400","please login first"));
            writer.write(errString);
            return false;
        }

        String userId = TokenUtils.resolveToken(token);

        System.out.println(requestURI);
        return true;
    }
}
